<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @sort-change="sortChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange">
      <template  #menu-left>
        <el-button type="warning" icon="el-icon-download"  @click="handleExport">导 出
        </el-button>
      </template>

      <template #customerNo-search="{ disabled, size }">
        <el-autocomplete
                style="width: 100%;"
                v-model="search.customerNo"
                :fetch-suggestions="queryCustomerNo"
                placeholder="请输入客户账号"
                :trigger-on-focus="false"
                @select="selectCustomerNo"
                :fit-input-width="true"
        ></el-autocomplete>
      </template>
      <template #customerName-search>
        <el-input v-model="search.customerName" readonly placeholder="请选择客户名称" @click="selectCustomerName" />
      </template>
      <template #factoryName-search>
        <el-input v-model="search.factoryName" readonly placeholder="请选择工厂信息" @click="selectFactory"/>
      </template>
      <template #companyName-search>
        <el-input v-model="search.companyName" readonly placeholder="请选择银行信息" @click="selectBankInfo" />
      </template>
    </avue-crud>
    <select-customer  ref="selectCustomer"  @success="setCustomerNo"/>
    <select-factory  ref="selectFactory"  @success="setFactory"/>
    <select-bank  ref="selectBank"  @success="setBank"/>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, reject, orderReport,checkCounterAudit} from "@/api/anwise/order/order";
  import {remoteList} from '@/api/anwise/customer/customer';
  import {mapGetters} from "vuex";
  import selectCustomer from './components/select_customer.vue';
  import selectFactory from './components/select_factory.vue';
  import selectBank from './components/select_bank.vue';
  import {Pattern} from "@/utils/validate.js";
  import { getToken } from '@/utils/auth';
  import { exportBlobPost } from '@/api/common';
  import { downloadXls } from '@/utils/util';
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';

  export default {
      components: {
          selectCustomer,
          selectFactory,
          selectBank
      },
    data() {
      return {
          isEnglish:'1',
          hiddenPrice:'1',
          selectId:'',
          box:false,
          form: {},
          query: {},
          salesDateRange:[],
          loading: false,
          dateFormat: 'YYYY-MM-DD',
          pickerOptions: {},
          page: {
              pageSize: 20,
              currentPage: 1,
              total: 0
          },
          search:{},
          selectionList: [],
          option: {
              height:'auto',
              calcHeight: 30,
              tip: false,
              searchShow: true,
              searchMenuSpan: 6,
              border: true,
              index: true,
              selection: true,
              reserveSelection:true,
              labelWidth: 150,
              indexWidth:100,
              menuWidth: 230,
              addBtn: false,
              editBtn: false,
              viewBtn: false,
              delBtn: false,
              stripe: true,
              searchIndex: 3,
              searchIcon: false,
            searchEnter:true,
              menu:false,
            // selectable:(row,index)=>{
            //   return row.orderStatus =='open';
            // },
          column: [

            {
              label: "订单编号",
              prop: "idNo",
              type: "input",
                fixed: true,
                overHidden: true,
                sortable: true,
                width:120,
              rules: [{
                required: true,
                message: "请输入订单编号",
                trigger: "blur"
              }],
            },
              {
                  label: "订单日期",
                  prop: "salesDate",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入订单日期",
                      trigger: "blur"
                  }],
              },
              {
                  label: "客户账号",
                  prop: "customerNo",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入客户账号",
                      trigger: "blur"
                  }],
              },
              {
                  label: "客户名称",
                  prop: "customerName",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入客户名称",
                      trigger: "blur"
                  }],
              },
              {
                  label: "销售方式",
                  prop: "salesType",
                  type: "select",
                  filterable: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  dicUrl: '/api/blade-system/dict-biz/dictionary?code=sales_type',
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入销售方式",
                      trigger: "blur"
                  }],
              },
              {
                  label: "订单状态",
                  prop: "orderStatus",
                  type: "select",
                  filterable: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  dicUrl: '/api/blade-system/dict-biz/dictionary?code=order_status',
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入订单状态",
                      trigger: "blur"
                  }],
              },
              {
                  label: "收款方",
                  prop: "companyName",
                  type: "input",
                  search:true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "工厂名称",
                  prop: "factoryName",
                  type: "input",
                  search:true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "客户PO",
                  prop: "custPo",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "联系人员",
                  prop: "contact",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "业务人员",
                  prop: "serviceName",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "交货地点",
                  prop: "deliAddr",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
            {
              label: "订单类型",
              prop: "orderType",
                type: "select",
                filterable: true,
                overHidden: true,
                sortable: true,
                width:120,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=order_type',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
                rules: [{
                    required: false,
                    message: "请输入订单类型",
                    trigger: "blur"
                }],
            },
            {
              label: "交货方式",
              prop: "deliMeth",
                type: "select",
                filterable: true,
                overHidden: true,
                sortable: true,
                width:120,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=deli_type',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
                rules: [{
                    required: false,
                    message: "请输入交货方式",
                    trigger: "blur"
                }],
            },

            {
              label: "付款条件",
              prop: "paymentTerms",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: '贸易条款',
              prop: 'tradeTerms',
              type: "input",
              overHidden: true,
              sortable: true,
              width:120,
            },
            {
              label: '运输方式',
              prop: 'tansportModes',
              type: "input",
              overHidden: true,
              sortable: true,
              width:120,
            },
              {
                  label: "币别",
                  prop: "rmb",
                  type: "select",
                  filterable: true,
                  // search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入币别",
                      trigger: "blur"
                  }],
              },

            {
              label: "收货人员",
              prop: "consignee",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "箱唛",
              prop: "salesName",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "生产备注",
              prop: "remark",
              type: "textarea",
              span: 24,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "销售备注",
              prop: "salesRemark",
              type: "textarea",
              span: 24,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "业务电话",
              prop: "extNo",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "订单日期",
              prop: "salesDate",
              type: "input",
                // search: true,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "补货备注",
              prop: "buhuoRemark",
              type: "textarea",
              span: 24,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "操作人员",
              prop: "createUserName",
              filterable: true,
              type: "input",
              // hide: true,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "操作时间",
              prop: "createTime",
              type: "input",
              // hide: true,
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "操作时间",
              prop: "createDate",
              type: "input",
              hide: true,
              sortable: true,
              width:150,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.order_add, false),
          viewBtn: this.validData(this.permission.order_view, false),
          delBtn: this.validData(this.permission.order_delete, false),
          editBtn: this.validData(this.permission.order_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
        handleExport() {
            if (this.selectionList.length === 0) {
                this.$message.warning("请选择至少一条数据");
                return;
            }
            console.log(this.ids);
            NProgress.start();
            exportBlobPost(
                    `/blade-/anwise/order/order/customInvoiceExcel?${this.website.tokenHeader
                    }=${getToken()}`,{ids:this.ids,factoryId:this.search.factoryId}
            ).then(res => {
              downloadXls(res.data, `清关发票、装箱单、CO${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
              NProgress.done();
            });
        },
        mounted() {
            this.loading = false;
        },
        setBank(row) {
            this.search.companyName = row.companyName;
            this.search.bankId = row.id;
        },
        selectBankInfo() {
            if (this.search.customerNo)  {
                this.$refs.selectBank.showSelect(this.search.customerId, 1);
            } else {
                this.$message({
                    type: "error",
                    message: "请先选择客户信息!"
                });
            }
        },
        setFactory(row) {
            if (row) {
                this.search.factoryId = row.id;
                this.search.factoryName = row.facName;
            }
        },
        selectFactory() {
            if (this.search.customerNo)  {
                this.$refs.selectFactory.showSelect(this.search.customerId);
            } else {
                this.$message({
                    type: "error",
                    message: "请先选择客户信息!"
                });
            }
        },
        setCustomerNo(row) {
            this.search.customerName = "";
            if (row) {
                this.search.customerId = row.id;
                this.search.customerNo = row.custNo;
                this.search.customerName = row.custName;}
        },
        selectCustomerName() {
            this.$refs.selectCustomer.showSelect();
        },

        queryCustomerNo(val,cb) {
            this.search.customerName = "";
            this.search.factoryName = "";
            const reg = Pattern.number;
            console.log(reg.test(val));
            if (!reg.test(val)) {
                this.$message({
                    type: "error",
                    message: "客户账号只能为数字!"
                });
                return;
            }

            remoteList(val).then(res => {
                if (res.data.success) {
                    let customerList = [];
                    res.data.data.forEach(item => {
                        customerList.push({
                            value:item.custNo +" - "+item.custName,
                            customerId: item.id,
                            customerNo: item.custNo,
                            customerName: item.custName,
                        });
                    })
                    cb(customerList);
                }
            })
        },
        selectCustomerNo(item) {
            console.log(item);
            this.search.customerId = item.customerId;
            this.search.customerNo = item.customerNo;
            this.search.customerName = item.customerName;
        },
        orderReport(id) {
            orderReport(this.selectId, this.isEnglish, this.hiddenPrice).then(res => {
                if(res.data.success) {
                    console.log(res.data)
                    const file = res.data.data;
                    // const originUrl = (file.url.replace(file.domain, `${this.res}/`));
                    const url = file.url;
                    // this.$refs.preview.open({
                    //     url: url || "",
                    //     originUrl: originUrl || ""
                    // });
                    window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
                }
            })
        },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
        sortChange(val) {
            console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoad(this.page);
        },
      searchReset() {
        this.query = {};
          this.search.customerId = "";
          this.search.customerNo = "";
          this.search.customerName = "";
          this.search.bankId = "";
          this.search.companyName = "";
          this.search.factoryId = "";
          this.search.factoryName = "";

          this.data=[];
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
        this.onLoad(this.page);
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
        this.onLoad(this.page);
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
            console.log(params);
          let filter = Object.assign(params, this.query);
            if (!filter.customerId || !filter.bankId || !filter.factoryId) {
                this.$message({
                    type: "error",
                    message: "请选择客户/收款方/工厂！!"
                });
                return;
            }
            params.searchType = 'custom_invoice';
        this.loading = true;
        getList(page.currentPage, page.pageSize, filter).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
    }
  };
</script>

<style>

  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button{
    -webkit-appearance: none !important;
    margin: 0;
  }
</style>
